package com.ruoyi.web.controller.yf;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.framework.responseBodyJson.CustomerJsonSerializer;
import com.ruoyi.framework.responseBodyJson.JSON;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.yf.domain.Report;
import com.ruoyi.yf.domain.YfTag;
import com.ruoyi.yf.service.IReportservice;
import com.ruoyi.yf.service.IYfTagService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.yf.domain.YfReportsConfig;
import com.ruoyi.yf.service.IYfReportsConfigService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 医废 报模版 配置Controller
 *
 * @author XiaoYi...
 * @date 2020-03-26
 * e8146506-e4df-4b59-8f6a-b14387ce3fb0
 */
@Controller
@RequestMapping("/yf/reports")
public class YfReportsConfigController extends BaseController {
    private String prefix = "yf/reports";

    @Autowired
    private IYfReportsConfigService yfReportsConfigService;

    @Autowired
    private IReportservice yfReportsService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private IYfTagService yfTagService;

    @Autowired
    private ISysConfigService configService;


    @RequiresPermissions("yf:reports:view")
    @GetMapping()
    public String reports() {
        return prefix + "/reports";
    }

    /**
     * 获取楼号
     *
     * @return
     * b4996a47-e6fa-4db7-91eb-d94e146316d0
     */
    @RequiresPermissions("yf:reports:list")
    @PostMapping("/buildingNoList")
    @ResponseBody
    public AjaxResult getBuildingNoList(Long hospitalId) {
        List<Integer> list = yfReportsConfigService.getBuildingNoList(hospitalId);
        return AjaxResult.successful(list);
    }

    /**
     * 获取采集员列表
     *
     * @return
     * eb712d4a-2b99-49e8-ad15-3e2bd8cdc938
     */
    @RequiresPermissions("yf:reports:list")
    @PostMapping("/collUserList")
    @ResponseBody
    public AjaxResult getCollUserList(Long hospitalId) {
        List<String> list = yfReportsConfigService.getCollUserList(hospitalId);
        return AjaxResult.successful(list);
    }

    /**
     * 获取科室列表
     *
     * @return
     * 7e299700-fbc7-47bc-b79e-fa648b69b107
     */
    @RequiresPermissions("yf:reports:list")
    @PostMapping("/KSList")
    @ResponseBody
    public AjaxResult getKSList(Long hospitalId) {
        List<String> list = yfReportsConfigService.KSList(hospitalId);
        return AjaxResult.successful(list);
    }

    /**
     * 获取医废类型列表 -- 判断是否有 胎盘
     *
     * @return
     * 402e509a-4678-4e7e-96b7-c23960ce4475
     */
    @RequiresPermissions("yf:reports:list")
    @PostMapping("/yfTypeList")
    @ResponseBody
    public AjaxResult getYfTypeList(Long hospitalId) {
        List<String> list = yfReportsConfigService.yfTypeList(hospitalId);
        return AjaxResult.successful(list);
    }

    /**
     * 查询医废 报模版 配置列表
     * b1bc26cd-227c-460b-82db-b27381e3bddb
     */
    @RequiresPermissions("yf:reports:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(YfReportsConfig yfReportsConfig) {
        startPage();
        List<YfReportsConfig> list = yfReportsConfigService.selectYfReportsConfigList(yfReportsConfig);
        return getDataTable(list);
    }

    /**
     * 导出医废 报模版 配置列表
     * 3495577f-105c-4e29-9eba-a51713444db0
     */
    @RequiresPermissions("yf:reports:export")
    @Log(title = "医废 报模版 配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(YfReportsConfig yfReportsConfig) {
        List<YfReportsConfig> list = yfReportsConfigService.selectYfReportsConfigList(yfReportsConfig);
        ExcelUtil<YfReportsConfig> util = new ExcelUtil<YfReportsConfig>(YfReportsConfig.class);
        return util.exportExcel(list, "reports");
    }

    /**
     * 新增医废 报模版 配置
     * 2fef4c85-8395-473a-9dcf-d2c1a2c38e36
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增医废 报模版 配置
     * 0bcd6289-b45b-4682-995a-b1e4e44ef271
     */
    @GetMapping("/add_new")
    public String add_new() {
        return prefix + "/add_new";
    }


    /**
     * 新增医废 报模版 配置
     * 4b37a15a-cede-4be0-8b18-94b61c7ee9f9
     */
    @GetMapping("/add_new2")
    public String add_new2() {
        return prefix + "/add_new2";
    }


    /**
     * @param pathName
     * @param mmap     打开页面、执行sql 等配置信息
     * @return java.lang.String
     * @author XiaoYi...
     * @date 2020/5/7 9:51
     * 53057584-0c96-487c-b8c1-c8799f1c1248
     */
    @GetMapping("/templates/{pathName}")
    public String openReports(@PathVariable("pathName") Long pathName, ModelMap mmap) throws JsonProcessingException {

        if (pathName == -1) {
            //测试预览模板
            mmap.put("test", true);
        } else {
            YfReportsConfig yfReportsConfig = yfReportsConfigService.selectYfReportsConfigById(pathName);
            //获取json 配置
            String jsonConfig = yfReportsConfig.getrTJson();
            mmap.put("jsonConfig", JSONArray.parse(jsonConfig));
            //报表标题
            String title = yfReportsConfig.getrTTitle();
            mmap.put("title", title);
            mmap.put("test", false);
            mmap.put("pathName", pathName);
        }
        mmap.put("userName", ShiroUtils.getSysUser().getUserName());
        mmap.put("hospName", ShiroUtils.getSysUser().getDept().getDeptName());
        return prefix + "/reportsTable";
    }

    /**
     * 新增医废 报模版 配置
     * 628a89cd-ba07-4d21-a322-bb3d42c6ae4c
     */
    public String getSql(String sql, Object hospitalId, String month, String startDate, String endDate, int buildingNo,
                         String collUser, String department, String yfType, String... parameter) {
        if (sql != null && !sql.isEmpty()) {
            SysUser sysUser = ShiroUtils.getSysUser();
            // 查询楼号
            if (buildingNo < 0) {
                sql = sql.replaceAll("[=]\\s+#\\{buildingNo}", "!= 99999");
            }else{//不查询楼号
                sql = sql.replaceAll("#\\{buildingNo}", String.valueOf(buildingNo));
            }
            // 查询 采集员
            if (collUser.equals("0")) {     // 不查询采集员
                sql = sql.replaceAll("[=]\\s+#\\{collUser}", "!= '99999'");
            }else{      // 查询指定采集员
                sql = sql.replaceAll("#\\{collUser}", "'" + collUser + "'" );
            }
            // 查询 科室
            if (department.equals("0")) {     // 不查询科室
                sql = sql.replaceAll("[=]\\s+#\\{department}", "!= '99999'");
            }else{      // 查询指定科室
                sql = sql.replaceAll("#\\{department}", "'" + department + "'" );
            }
            // 查询 医废类型
            if (yfType.equals("0")) {     // 不查询医废类型
                sql = sql.replaceAll("[=]\\s+#\\{yfType}", "!= '99999'");
            }else{      // 查询指定医废类型
                sql = sql.replaceAll("#\\{yfType}", "'" + yfType + "'" );
            }
            return sql.replaceAll("#\\{hospitalId}", hospitalId.toString())//替换医院id
                    .replaceAll("#\\{deptId}", sysUser.getDeptId().toString())//替换医院id
                    .replaceAll("#\\{sysUserId}", sysUser.getUserId().toString())//替换用户id  -- 暂时未使用
                    .replaceAll("#\\{month}", month.isEmpty() ? "" : month) //月份
                    .replaceAll("#\\{startDate}", startDate.isEmpty() ? "" : startDate)//开始时间
                    .replaceAll("#\\{endDate}", endDate.isEmpty() ? "" : endDate);//结束时间
        }
        return sql;
    }

//    public static void main(String[] args) {
//        String str = "SELECT\n" +
//                "\t`s`.`dept_id` AS `s1`,\n" +
//                "\t`s`.`dept_name` AS `s2`,\n" +
//                "\t`d`.`dept_name` AS `s3`,\n" +
//                "\tsum(if(t.trash_type=1,t.weight,0)) as 'd1',\n" +
//                "\tsum(if(t.trash_type=1,t.bag,0)) as 'i1',\n" +
//                "\t\n" +
//                "\tsum(if(t.trash_type=2,t.weight,0)) as 'd2',\n" +
//                "\tsum(if(t.trash_type=2,t.bag,0)) as 'i2',\n" +
//                "\t\n" +
//                "\tsum(if(t.trash_type=3,t.weight,0)) as 'd3',\n" +
//                "\tsum(if(t.trash_type=3,t.bag,0)) as 'i3',";
//        System.out.println(str.replaceAll("[\n](\\s)*", " "));
//    }

    //模板数据查询
//    e6140f19-80aa-42e6-ad18-c6502af7d215
    @RequestMapping(value = "/templatesList", method = RequestMethod.POST)
    @ResponseBody
    public TableDataInfo openReportsList(@RequestParam long hospitalId, @RequestParam long configId,
            @RequestParam(required = false) String month, @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate, @RequestParam(required = false) String sql,
            @RequestParam(required = false) String selectNameSort, @RequestParam(required = false) int buildingNo,
            @RequestParam(required = false) String collUser, @RequestParam(required = false) String department,
            @RequestParam(required = false) String yfType, @RequestParam boolean test) throws JsonProcessingException {

//        System.out.println("报表id：" + configId + ";医院id：" + hospitalId + ";时间范围" + startDate + "-" + endDate + sql);

        if (!test) {
            //非测试 预览
            YfReportsConfig yfReportsConfig = yfReportsConfigService.selectYfReportsConfigById(configId);
            //获取所需显示的列
            selectNameSort = yfReportsConfig.getSelectNameSort();
            sql = yfReportsConfig.getrTSql();
        }

        sql = getSql(sql, hospitalId, month, startDate, endDate, buildingNo, collUser, department, yfType);
        //获取sql
        logger.info("[完整替换后sql>>>][{}]", sql.replaceAll("[\n](\\s)*", " "));
        //sql 查询数据
        List<Report> reports = yfReportsService.report_select_sql(sql);
        //过滤返回数据
        CustomerJsonSerializer cjs = new CustomerJsonSerializer();

        cjs.filter(Report.class, selectNameSort, null);
        //返回结果json
        JSONArray jsonObject = new JSONArray();
        for (Report re : reports) {
            String include = cjs.toJson(re);
            JSONObject json = JSONObject.parseObject(include);
            jsonObject.add(json);
        }
        return getDataTable(jsonObject);
    }

    //todo 测试数据 集合
//    165909b9-7436-4216-b806-57e2b3d85618
    @PostMapping("/exSql")
    @ResponseBody
    @JSON(filter = "user,dept", type = YfTag.class)
    public TableDataInfo sql() {
        YfTag yfTag = new YfTag();
        yfTag.setSourceDeptId(Long.valueOf("20200611120001"));
        List<YfTag> yfTags = yfTagService.selectYfTagList(yfTag);
        return getDataTable(yfTags);
    }

    /**
     * @param yfReportsConfig 新增保存医废 报模版 配置
     * @return
     * @author XiaoYi...
     * @date 2020/5/7 9:51
     * c74332f8-e703-4269-b3a0-8e22d66e1b19
     */
    @RequiresPermissions("yf:reports:add")
    @Log(title = "医废 报模版 配置", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(YfReportsConfig yfReportsConfig) {

        //自动添加菜单
        SysMenu sysMenu = new SysMenu();
        sysMenu.setMenuName(yfReportsConfig.getrTName());
        sysMenu.setParentId(Long.valueOf(2009));
        sysMenu.setOrderNum("200");
        sysMenu.setMenuType("C");
        sysMenu.setVisible("0");
        sysMenu.setPerms("");
        sysMenu.setIcon("#");
        SysUser sysUser = ShiroUtils.getSysUser();
        sysMenu.setCreateBy(sysUser.getUserName());
//        sysMenu.setCreateTime(new Date());
        sysMenu.setCreateId(sysUser.getUserId());
        sysMenu.setRemark(yfReportsConfig.getRemark());

        yfReportsConfig.setCreateId(ShiroUtils.getSysUser().getUserId());

        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(sysMenu))) {
            return error("新增菜单'" + sysMenu.getMenuName() + "'失败，菜单名称已存在");
        }

//        yfReportsConfig.setrTJson(yfReportsConfig.getrTJson().replaceAll("\\r|\\t|\\n|\\s", ""));
        sysMenu.setCreateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();


        int i = yfReportsConfigService.insertYfReportsConfig(yfReportsConfig);
        if (i >= 1) {
            sysMenu.setUrl("/yf/reports/templates/" + yfReportsConfig.getId());
            return toAjax(menuService.insertMenu(sysMenu));
        }
        return AjaxResult.error("菜单创建失败");
    }

    /**
     * 修改医废 报模版 配置
     * 7af183ec-662d-4469-9ab5-d4752f8dbb32
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        YfReportsConfig yfReportsConfig = yfReportsConfigService.selectYfReportsConfigById(id);
        mmap.put("yfReportsConfig", yfReportsConfig);
        return prefix + "/edit";
    }

    /**
     * 修改保存医废 报模版 配置
     * 1d74ebb5-564d-4fbf-859e-32ad55b4c420
     */
    @RequiresPermissions("yf:reports:edit")
    @Log(title = "医废 报模版 配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(YfReportsConfig yfReportsConfig) {
        yfReportsConfig.setUpdateId(ShiroUtils.getSysUser().getUserId());
        return toAjax(yfReportsConfigService.updateYfReportsConfig(yfReportsConfig));
    }

    /**
     * 删除医废 报模版 配置
     * 86f4ca65-a990-49be-b366-e7e8259df69a
     */
    @RequiresPermissions("yf:reports:remove")
    @Log(title = "医废 报模版 配置", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(yfReportsConfigService.deleteYfReportsConfigByIds(ids));
    }


}
